// pages/goodsDetail/seckillDetail/seckillDetail.js
const app = getApp()
const WxParse = require('../../../wxParse/wxParse.js');
Page({
  /**
   * 页面的初始数据
   */
  data: {
    imgUrls: [],
    indicatorDots: true,
    autoplay: false,
    interval: 5000,
    duration: 1000,
    number: 1,
    typeindex: -1,
    show: false,
    product: {},
    type: [], //类型名字
    typeprce: [], //类型价格
    endtime: 0,
    day: '',
    hour: 0,
    min: 0,
    second: 0,
    timer: '',
    cartype: '', //判断规格是否选择
    carnum: '',
    sid: '',
    nullshow: false,
    rich:'',
    poster: '',
    qrshow: false,
  },

  bindsave(e) {
    let that = this
    let image = ''
    if (e.currentTarget.dataset.url) {
      image = e.currentTarget.dataset.url
      console.log(image)
    } else if (e.currentTarget.dataset.rich) {
      let rich = e.currentTarget.dataset.rich
      let img1 = rich.split('src="')[1];
      let img2 = img1.split('"')[0]
      image = img2.replace(/\"/g, "");
      console.log(1, img1, 2, img2)
      console.log(image)
    }

    wx.getImageInfo({
      src: image,
      success: function (res) {
        console.log(res)
        let imageWX = res.path
        wx.saveImageToPhotosAlbum({
          filePath: imageWX,
          success: (res) => {
            wx.showToast({
              title: "已保存到相册",
              icon: 'none',
              duration: 2000,
              mask: true
            })
          },
          fail: function (res) {
            console.log(res)
            //首次保存会询问你是否授权，选是就好了
            if (res.errMsg == "saveImageToPhotosAlbum:fail auth deny") {
              that.setData({ istrue: true })
            }
          }
        })
      }
    })
  },
  // 获取授权
  bindimpower() {
    wx.openSetting({
      success(settingdata) {
        console.error(settingdata)
        if (settingdata.authSetting["scope.writePhotosAlbum"]) {
          console.log("获取权限成功，再次点击图片保存到相册")
        } else {
          console.log("获取权限失败")
        }
      }
    })
  },
  //转发
  onShareAppMessage(res) {
    return {
      title: '宝芝林',
      path: '/pages/login/welcome?scene=' + this.data.uid
    }
  },
  // 加
  bindPlus() {
    let number = this.data.number
    number++
    this.setData({
      number: number
    })
  },
  // 减
  bindMinus() {
    let number = this.data.number
    if (number > 1) {
      number--
    }
    this.setData({
      number: number
    })
  },
  // 选择规格
  chooseType: function(e) {
    let typeindex = e.currentTarget.dataset.idx
    let item = e.currentTarget.dataset.item
    this.setData({
      typeindex: typeindex,
      cartype: item
    })
  },
  // 显示
  typebox() {
    this.setData({
      show: true
    })
    console.log(this.data.show)
  },
  // 隐藏
  typeboxhidden() {
    this.setData({
      show: false
    })
    console.log(this.data.show)
  },
  // 跳评论
  jumpspeak() {
    wx.navigateTo({
      url: '/pages/speak/speak',
    })
  },
  //客服
  jumphelp() {
    wx.navigateTo({
      url: '/pages/person/help/help',
    })
  },
  // 加购物车
  addcars() {
    let that = this
    if (that.data.cartype == '') {
      that.setData({
        show: true
      })
      wx.showToast({
        title: '请选择具体规格',
        icon: 'none'
      })
    } else {
      wx.request({
        url: app.globalData.api + "addcart",
        data: {
          uid: that.data.uid,
          gid: that.data.product.id,
          num: that.data.number,
          price: that.data.typeprce[that.data.typeindex],
          guige: that.data.cartype,
          yunfei: that.data.product.yunfei,
          type: 1
        },
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        method: "POST",
        success: function(res) {
          console.log(res)
          if (res.data.code == 0) {
            wx.showToast({
                title: '添加成功',
                icon: 'success',
                duration: 2000
              }),
              that.setData({
                show: false,
                cartype: '',
                typeindex: -1,
                number: 1,
                carnum: res.data.count
              })
          } else {
            wx.showToast({
              title: res.data.msg,
              icon: 'none',
              duration: 2000
            })
          }
        },
      })
    }
  },
  //购买
  buynow() {
    let that = this
    let good = []
    good = [{
      gid: that.data.product.id,
      num: that.data.number,
      guige: that.data.cartype,
      price: that.data.product.newprice,
      type: 1
    }]

    let carts = []
    carts.push({
      gid: that.data.product.id,
      num: that.data.number,
      price: that.data.typeprce[that.data.typeindex],
      yunfei: that.data.product.yunfei,
      type: 1
    })
    let detail = []
    detail.push(that.data.product)
    let final = Object.assign(detail[0], good[0]); //最终对象
    let finalarray = []
    finalarray.push(final)
    console.log('最终数组', finalarray)
    let car = (encodeURIComponent(JSON.stringify(finalarray))) //商品数据
    if (that.data.cartype == '') {
      that.setData({
        show: true
      })
      wx.showToast({
        title: '请选择具体规格',
        icon: 'none'
      })
    } else {
      carts = JSON.stringify(carts)
      // 获取的计算总价
      wx.request({
        url: app.globalData.api + "getcarttotal",
        data: {
          uid: that.data.uid,
          level: that.data.level,
          carts: carts,
        },
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        method: "POST",
        success: function(res) {
          console.log('总价', res)
          console.log(that.data.sid)
          if (res.data.code == 1) {
            wx.showToast({
              title: res.data.msg,
              icon: 'none'
            })
          } else {
            wx.navigateTo({
              url: '/pages/buynow/buynow?uid=' + that.data.uid + '&sid=' + that.data.sid + '&goods=' + car + '&total=' + res.data.total + '&price=' + res.data.price + '&yunfei=' + that.data.product.yunfei + '&num=' + that.data.number + '&guige=' + that.data.cartype
            })
          }
        },
      })
    }
  },
  //跳购物车
  jumpcar() {
    wx.switchTab({
      url: '/pages/car/carIndex',
    })
  },
  // 倒计时
  countDown: function() {
    let that = this
    // let now = (new Date()).valueOf();
    that.setData({
      timer: setInterval(function() {
        let now = (new Date()).valueOf();
        now = Number(now);
        // console.log('now',now)
        // console.log('end', that.data.endtime * 1000)
        let time = that.data.endtime * 1000 - now
        // console.log(time)
        let day = parseInt(time / 1000 / 60 / 60 / 24)
        let hour = parseInt(time / 1000 / 60 / 60 % 24)
        let min = parseInt(time / 1000 / 60 % 60)
        let second = parseInt(time / 1000 % 60)
        that.setData({
          hour: hour,
          min: min,
          second: second,
          day: day
        })
      }, 1000)
    })
  },
  // 获取海报
  getqr() {
    wx.request({
      url: app.globalData.api + "getposter",
      data: {
        uid: this.data.uid,
        level: this.data.level,
        id: this.data.id,
        type: 2
      },
      success: (res) => {
        console.log('海报', res)
        this.setData({
          poster: res.data.img,
          qrshow: true
        })

      },
    })
  },
  close() {
    this.setData({
      qrshow: false
    })
  },
  // 保存海报
  saveposter() {
    wx.getImageInfo({
      src: this.data.poster,
      success: (res) => {
        console.log(res)
        let imageWX = res.path
        wx.saveImageToPhotosAlbum({
          filePath: imageWX,
          success: (res) => {
            wx.showToast({
              title: "已保存到相册",
              icon: 'none',
              duration: 2000,
              mask: true
            })
            this.setData({
              qrshow: false
            })
          },
          fail: (res) => {
            console.log(res)
            //首次保存会询问你是否授权，选是就好了
            if (res.errMsg == "saveImageToPhotosAlbum:fail auth deny") {
              that.setData({ istrue: true })
            }
          }
        })
      }
    })
  },
  // 获取授权
  bindimpower() {
    wx.openSetting({
      success(settingdata) {
        console.error(settingdata)
        if (settingdata.authSetting["scope.writePhotosAlbum"]) {
          console.log("获取权限成功，再次点击图片保存到相册")
        } else {
          console.log("获取权限失败")
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var change = require('../../../utils/util.js');
    let that = this
    let time = 0
    console.log(options)

    wx.getStorage({
      key: 'userinfo',
      success: function(res) {
        console.log(res.data.id)
        that.setData({
          uid: res.data.id,
          level: res.data.level,
          sid: res.data.sid,
          id: options.id,
        })
        wx.request({
          url: app.globalData.api + "getspikedetail",
          data: {
            id: options.id,
            uid: res.data.id
          },
          success: function(res) {
            console.log(res)
            if (res.data.code == 1) {
              that.setData({
                nullshow: true
              })
            } else {
              let type = res.data.list.v1
              let typelist = new Array()
              typelist = type.split('|')
              let type2 = res.data.list.p1
              let typeprce = new Array()
              typeprce = type2.split('|')
              let endtime = res.data.list.endtime
              let lunbo = res.data.list.img
              let imgbox = new Array()
              imgbox = lunbo.split(',')
              let rich = res.data.list.content.replace(/<img /g, '<img class="rich_img"')
              WxParse.wxParse('article', 'html', res.data.list.content, that, 5);
              that.setData({
                product: res.data.list,
                carnum: res.data.count,
                type: typelist,
                typeprce: typeprce,
                endtime: endtime,
                imgUrls: imgbox,
                sid: that.data.sid,
                rich: rich
              })
            }
         
          },
        })
      },
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.countDown()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

})